import scala.collection.mutable.ArrayBuffer

case class HittableList() extends Hittable:
  val list: ArrayBuffer[Hittable] = ArrayBuffer()
  def add(hittable: Hittable) = list.addOne(hittable)
  def clear() = list.clear

  override def hit(r: Ray, t_min: Double, t_max: Double): Option[HitRecord] =
    val init: Option[HitRecord] = None
    list.foldLeft(init){(record, hittable) =>
      record match
        case Some(rec) =>
          val new_record = hittable.hit(r, t_min, rec.t)
          if new_record.isEmpty then record else new_record
        case None => hittable.hit(r, t_min, t_max)
    }